package com.ds.esd.admin.handler;


import com.alibaba.fastjson.JSONObject;
import com.ds.common.JDSException;
import com.ds.common.md5.MD5InputStream;
import com.ds.config.ErrorResultModel;
import com.ds.config.ResultModel;
import com.ds.esd.admin.node.XUIFile;
import com.ds.esd.dsm.DSMFactory;
import com.ds.esd.dsm.enums.ThumbnailType;
import com.ds.server.httpproxy.core.*;
import com.ds.server.httpproxy.handler.ResourceHandler;
import com.ds.server.httpproxy.handler.multipart.SimpleRequestContext;
import com.ds.vfs.VFSConstants;
import com.ds.vfs.ct.CtVfsFactory;
import com.ds.vfs.ct.CtVfsService;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.portlet.PortletFileUpload;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import java.util.regex.Pattern;


public class ThumbnailUPLoadHandler extends AbstractHandler {

    private static final Logger log = Logger.getLogger(ResourceHandler.class.getName());
    public static final ConfigOption RULE_OPTION = new ConfigOption("rule", true, "Regular expression for matching URLs.");

    Pattern rule;

    public boolean initialize(String handlerName, Server server) {
        super.initialize(handlerName, server);
        rule = Pattern.compile(RULE_OPTION.getProperty(server, handlerName));
        return true;
    }


    protected boolean handleBody(HttpRequest request, HttpResponse response) throws IOException {
        String resource = request.getPath();
        boolean ruleMatches = rule.matcher(resource).matches();
        if (!ruleMatches) {
            return false;
        }
        String mimeType = getMimeType(resource);
        if (mimeType != null) {
            response.setMimeType(mimeType);
        }
        String contentType = this.getContentType(request);
        if (contentType != null && contentType.indexOf("multipart/form-data") > -1) {
            return this.sendMultiparPostProxy(request, response);
        }

        return true;
    }


    public boolean sendMultiparPostProxy(HttpRequest request, HttpResponse response) throws IOException {
        Map<String, String> params = new HashMap<String, String>();
        // 获取服务器响应的IO流
        RequestContext requestContext = new SimpleRequestContext(StandardCharsets.UTF_8, this.getContentType(request), new ByteArrayInputStream(request.getPostData()));
        // 解析器创建
        FileUploadBase fileUploadBase = new PortletFileUpload();
        FileItemFactory fileItemFactory = new DiskFileItemFactory();
        fileUploadBase.setFileItemFactory(fileItemFactory);
        fileUploadBase.setHeaderEncoding(VFSConstants.CONFIG_CTVFS_KEY);
        ThumbnailType thumbnailType = null;


        // 解析出所有的部件
        List<FileItem> fileItems = null;
        try {
            fileItems = fileUploadBase.parseRequest(requestContext);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

        ResultModel<XUIFile> result = new ResultModel<XUIFile>();
        for (FileItem f : fileItems) {
            if (f.isFormField()) {
                if (f != null && f.get() != null && f.get().length > 0) {
                    params.put(f.getFieldName(), f.getString("utf-8"));
                }
            }
        }
        String thumbnailTypeStr = request.getParameter("thumbnailType");
        if (thumbnailTypeStr == null || thumbnailTypeStr.equals("")) {
            thumbnailTypeStr = params.get("thumbnailType");
        }

        if (thumbnailTypeStr != null && !thumbnailTypeStr.equals("")) {
            thumbnailType = ThumbnailType.formType(thumbnailTypeStr);
        }
        for (FileItem f : fileItems) {
            if (!f.isFormField()) {
                String viewInstId = null;
                if (thumbnailType != null) {
                    viewInstId = params.get(thumbnailType.getPkName());
                }
                String files_fullname = params.get("files_fullname");
                try {
                    if (thumbnailType != null && viewInstId != null) {
                        DSMFactory.getInstance().getTempManager().uploadThumbnail(new MD5InputStream(f.getInputStream()), files_fullname, viewInstId, thumbnailType);
                    } else {
                        result = new ErrorResultModel<>();
                        ((ErrorResultModel) result).setErrdes("thumbnailType is null!");
                    }

                } catch (JDSException e) {
                    result = new ErrorResultModel<>();
                    ((ErrorResultModel) result).setErrdes(e.getMessage());
                }

            }
        }

        response.sendJSONResponse(JSONObject.toJSONString(result));
        return true;


    }


    public CtVfsService getVfsClient() {

        CtVfsService vfsClient = CtVfsFactory.getCtVfsService();
        return vfsClient;
    }

    public String getContentType(HttpRequest request) {

        String contentType = request.getRequestHeader("Content-Type");
        if (contentType == null) {
            contentType = request.getRequestHeader("Content-type");
        }
        return contentType;
    }


}
